import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login.vue'
import Layout from '@/views/Layout.vue'
import Article from '@/views/Article.vue'
import Question from '@/views/Question.vue'
import Video from '@/views/Video.vue'
import User from '@/views/User.vue'
import Detail from '@/views/Detail.vue'
import Search from '@/views/Search.vue'
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)

const router = new VueRouter({
    routes: [
        { path: '/login', component: Login },
        { path: '/', redirect: '/article' },
        {
            path: '/', component: Layout, children: [
                { path: '/article', component: Article },
                { path: '/question', component: Question },
                { path: '/video', component: Video },
                { path: '/user', component: User }
            ]
        },
        { path: '/detail/:id', component: Detail },
        { path: '/search', component: Search },
    ]
})

const whiteList = ['/login', '/article']
router.beforeEach((to, from, next) => {
    if (getToken()) {
        next()
    } else {
        if (whiteList.includes(to.path)) {
            next()
        } else {
            next('/login')
        }
    }
})

export default router
